package com.it.gw.modules.water.activity.pump

import LoginVo
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.it.common.bean.MapDataBean
import com.it.common.utils.DisplayUtil
import com.it.common.utils.GsonUtils
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.isNotEmpty
import com.it.common.utils.tr
import com.it.data.manager.AppCacheManager
import com.it.data.network.req.PumpRecordDto
import com.it.data.network.req.UploadFileDto
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.data.PhotoBean
import com.it.gw.databinding.ActivityPumpItemDetailBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.manager.DictionariesManager.ADM_DEP
import com.it.gw.manager.DictionariesManager.ENG_GRAD_1
import com.it.gw.manager.DictionariesManager.ENG_SCAL_1
import com.it.gw.manager.DictionariesManager.ENG_STAT
import com.it.gw.manager.DictionariesManager.MAIN_BUILD_GRAD
import com.it.gw.manager.DictionariesManager.PUST_TYPE
import com.it.gw.modules.map.activity.MapActivity
import com.it.gw.modules.water.adapter.SelectPhotoAdapter
import com.it.gw.modules.water.viewmodel.WaterViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.io.File

//泵站详情
class PumpItemDetailActivity : BaseActivity<ActivityPumpItemDetailBinding>() {
    private val waterViewModel by viewModels<WaterViewModel>()
    private val photos = mutableListOf<PhotoBean>()
    private var selectPhotoAdapter: SelectPhotoAdapter? = null

    companion object {
        const val TAG = "PumpItemDetailActivity"
    }


    override fun initObserver() {
        waterViewModel.pumpRecordDtoDetailLiveData.observe(this) {
            ProgressDialog.hide()
            Log.d(TAG, "pumpRecordDtoDetailLiveData: ${it}")
            if (it.result && it.data.isNotEmpty()) {
                setDetailView(it.data!!)
            }

        }
        waterViewModel.insertLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(this, "操作成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_SHORT).show()
            }

        }

    }

    private fun setDetailView(data: PumpRecordDto) {
        binding.pustCode.setText(data.pustCode.tr()) // 泵站代码
        binding.pustName.setText(data.pustName.tr()) // 泵站名称
        binding.lgtd.setText(data.lgtd.tr()) // 泵站经度
        binding.lttd.setText(data.lttd.tr()) // 泵站纬度
        binding.pustLoc.setText(data.pustLoc.tr()) // 泵站所在位置
        // binding.pustType.setText(data.pustType) // 泵站类型（1 排水泵站 2 供水泵站 3 供排结合泵站）


        //泵站类型
        binding.pustType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(PUST_TYPE),
                code = data.pustType.tr()
            )
        )

        binding.insFlow.setText(data.insFlow.tr()) // 装机流量
        binding.insPow.setText(data.insPow.tr()) // 装机功率
        binding.pumpNum.setText(data.pumpNum.tr()) // 水泵数量
        binding.desHead.setText(data.desHead.tr()) // 设计扬程
        binding.engTask.setText(data.engTask.tr()) // 工程任务
        // binding.engGrad.setText(data.engGrad) // 工程等别（（1 Ⅰ 2 Ⅱ 3 Ⅲ 4 Ⅳ 5 Ⅴ））

        //工程等别
        binding.engGrad.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ENG_GRAD_1),
                code = data.engGrad.tr()
            )
        )

        //  binding.engScal.setText(data.engScal) // 工程规模 （1 大（1）型 2 大（2）型 3 中型 4 小（1）型 5 小（2）型 9 其他）

        //工程规模
        binding.engScal.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ENG_SCAL_1),
                code = data.engScal.tr()
            )
        )

        //  binding.mainBuildGrad.setText(data.mainBuildGrad) // 主要建筑物级别 （1 1级 2 2级 3 3级 4 4级 5 5级 9 其他）


        //主要建筑物级别
        binding.mainBuildGrad.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD),
                code = data.mainBuildGrad.tr()
            )
        )

        // binding.engStat.setText(data.engStat) // 工程建设情况 （0 在建 1 已建 2 未建）

        //主要建筑物级别
        binding.engStat.setText(

            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ENG_STAT),
                code = data.engStat.tr()
            )
        )


        binding.startDate.setText(data.startDate.tr()) // 开工时间
        binding.compDate.setText(data.compDate.tr()) // 建成时间
        // binding.admDep.setText(data.admDep) // 归口管理部门 （0 未知 1 水利部门 2 电力部门 3 农业部门 4 林业部门 5 城建部门 6 航运部门 7 环保部门 9 其他部门）

        //归口管理部门
        binding.admDep.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ADM_DEP),
                code = data.admDep.tr()
            )
        )

        binding.note.setText(data.note.tr()) // 更新备注
        binding.opinion.setText(data.opinion.tr())
        //显示文件图片
        if (data.fileList.isNotEmpty()) {
            val list =
                data.fileList?.map { PhotoBean(filePath = "", id = it.id, url = it.filePath) }
            photos.clear()
            if (list != null) {
                photos.addAll(list)
                selectPhotoAdapter?.notifyDataSetChanged()
            }
        }


    }


    override fun initListener() {
        binding.rlUpload.setOnClickListener {
            showPicSelect { type ->
                if (type == 1) {
                    takePhoto { path ->
                        Log.d(TAG, "onBindViewHolder: takePhoto ${it}")
                        uploadFile(path)

                    }
                } else if (type == 2) {
                    pickMedia { path ->
                        Log.d(TAG, "onBindViewHolder: pickMedia ${it}")
                        uploadFile(path)
                    }
                }

            }

        }
        binding.lgtd.setOnClickListener {
            startLocation()
        }
        binding.lttd.setOnClickListener {
            startLocation()
        }

        binding.btnSave.setOnClickListener {
            insertSluiceRecord()

        }
        binding.pustType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(PUST_TYPE)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.pustType.text =
                            DictionariesManager.dictionariesMap.get(PUST_TYPE)!![index].ITEMNAME

                    })
            }
        }

        binding.engGrad.setOnClickListener {
            DictionariesManager.dictionariesMap.get(ENG_GRAD_1)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.engGrad.text =
                            DictionariesManager.dictionariesMap.get(ENG_GRAD_1)!![index].ITEMNAME

                    })
            }
        }
        binding.engScal.setOnClickListener {
            DictionariesManager.dictionariesMap.get(ENG_SCAL_1)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.engScal.text =
                            DictionariesManager.dictionariesMap.get(ENG_SCAL_1)!![index].ITEMNAME

                    })
            }
        }
        binding.mainBuildGrad.setOnClickListener {
            DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.mainBuildGrad.text =
                            DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD)!![index].ITEMNAME

                    })
            }
        }

        binding.engStat.setOnClickListener {
            val list = DictionariesManager.dictionariesMap.get(ENG_STAT)
            Log.d(TAG, "initListener:list====== ${list}")
            DictionariesManager.dictionariesMap.get(ENG_STAT)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.engStat.text =
                            DictionariesManager.dictionariesMap.get(ENG_STAT)!![index].ITEMNAME

                    })
            }
        }

        binding.admDep.setOnClickListener {
            DictionariesManager.dictionariesMap.get(ADM_DEP)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.admDep.text =
                            DictionariesManager.dictionariesMap.get(ADM_DEP)!![index].ITEMNAME

                    })
            }
        }


        binding.compDate.setOnClickListener {
            showDatePickerDialog(selectDateAction = {
                binding.compDate.text = it
            })
        }
        binding.startDate.setOnClickListener {
            showDatePickerDialog(selectDateAction = {
                binding.startDate.text = it
            })
        }

    }

    private fun uploadFile(path: String?) {
        lifecycleScope.launch {
            runCatching {
                ProgressDialog.show(this@PumpItemDetailActivity)
                val uploadFileDtoList = mutableListOf<UploadFileDto>()
                val file = File(path)
                uploadFileDtoList.add(UploadFileDto(file = file, fileName = file.name))
                val res = waterViewModel.upload(uploadFileDtoList)
                ProgressDialog.hide()
                if (res.success == true) {
                    photos.add(PhotoBean(filePath = path, id = res.data))
                    selectPhotoAdapter?.notifyDataSetChanged()
                } else {
                    Toast.makeText(
                        this@PumpItemDetailActivity,
                        "上传文件失败${res.message}",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }.onFailure {
                ProgressDialog.hide()
                Toast.makeText(
                    this@PumpItemDetailActivity,
                    "上传文件失败${it.message}",
                    Toast.LENGTH_LONG
                ).show()
            }
        }

    }

    private fun insertSluiceRecord() {
        ProgressDialog.show(this)
        val loginVo = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)
        val dto = PumpRecordDto(
            lgtd = binding.lgtd.text.toString(), // 泵站经度
            lttd = binding.lttd.text.toString(), // 泵站纬度
            pustCode = binding.pustCode.text.toString(), // 泵站代码
            pustName = binding.pustName.text.toString(), // 泵站名称
            pustLoc = binding.pustLoc.text.toString(), // 泵站所在位置
//            pustType = binding.pustType.text.toString(), // 泵站类型（1 排水泵站 2 供水泵站 3 供排结合泵站）
            pustType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(PUST_TYPE),
                name = binding.pustType.text.toString()
            ),

            insFlow = binding.insFlow.text.toString(), // 装机流量
            insPow = binding.insPow.text.toString(), // 装机功率
            pumpNum = binding.pumpNum.text.toString(), // 水泵数量
            desHead = binding.desHead.text.toString(), // 设计扬程
            engTask = binding.engTask.text.toString(), // 工程任务
//            engGrad = binding.engGrad.text.toString(), // 工程等别（（1 Ⅰ 2 Ⅱ 3 Ⅲ 4 Ⅳ 5 Ⅴ））
            engGrad = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ENG_GRAD_1),
                name = binding.engGrad.text.toString()
            ),

            //  engScal = binding.engScal.text.toString(), // 工程规模 （1 大（1）型 2 大（2）型 3 中型 4 小（1）型 5 小（2）型 9 其他）
            engScal = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ENG_SCAL_1),
                name = binding.engScal.text.toString()
            ),
            // mainBuildGrad = binding.mainBuildGrad.text.toString(), // 主要建筑物级别 （1 1级 2 2级 3 3级 4 4级 5 5级 9 其他）

            mainBuildGrad = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD),
                name = binding.mainBuildGrad.text.toString()
            ),

            //  engStat = binding.engStat.text.toString(), // 工程建设情况 （0 在建 1 已建 2 未建）
            engStat = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ENG_STAT),
                name = binding.engStat.text.toString()
            ),


            startDate = binding.startDate.text.toString(), // 开工时间
            compDate = binding.compDate.text.toString(), // 建成时间
            // admDep = binding.admDep.text.toString(), // 归口管理部门 （0 未知 1 水利部门 2 电力部门 3 农业部门 4 林业部门 5 城建部门 6 航运部门 7 环保部门 9 其他部门）

            admDep = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ADM_DEP),
                name = binding.admDep.text.toString()
            ),
            note = binding.note.text.toString() // 更新备注
        )

        dto.state = "1"
        dto.type = dataType
        dto.inputAddvcd = loginVo?.depId
        dto.inputBy = loginVo?.id
        val picPath = photos.joinToString(",", transform = {
            it.id!!
        })
        dto.picPath = picPath
        waterViewModel.insertPumpRecord(dto)

    }

    override fun initData() {
        ProgressDialog.show(this)
        getData()
    }

    var dataType = "ADD"//数据操作类型
    private fun getData() {


        val operationType = intent.getStringExtra("operationType")
        val guid = intent.getStringExtra("guid")
        val type = intent.getStringExtra("type")
        val state = intent.getStringExtra("state")

        //审核详情
        if ("opinion" == operationType) {
            waterViewModel.getAfterPumpParam(guid, type)
            if (state!!.contains("待")) {
                binding.btnSave.visibility = View.GONE
                binding.llReason.visibility = View.GONE
                binding.rlUpload.isEnabled = false
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_B2B3BB))
                dataType = ""
            } else if (state.contains("已")) {
                binding.btnSave.visibility = View.GONE
                binding.llReason.visibility = View.GONE
                binding.rlUpload.isEnabled = false
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_B2B3BB))
                dataType = ""
            } else {
                dataType = "UPDATE"
                binding.btnSave.visibility = View.VISIBLE
                binding.llReason.visibility = View.VISIBLE
                binding.rlUpload.isEnabled = true
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_0F6AF8))
            }

        } else {
            dataType = "ADD"
            waterViewModel.getPumpBasic(intent.getStringExtra("id")!!)
            binding.llReason.visibility = View.GONE
            binding.rlUpload.isEnabled = true
            binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_0F6AF8))

        }

    }


    var title = ""
    override fun initView() {
        title = "${intent.getStringExtra("title")}"
        setTitle(
            title = title,
            isBack = true,
            tvRightRes1 = R.string.str_location,
            tvRight1Action = {
                val intent = Intent(this, MapActivity::class.java)
                intent.putExtra("title", title)
                val mapList = mutableListOf(
                    MapDataBean(
                        name = title,
                        lgtd = binding.lgtd.text.toString(),
                        lttd = binding.lttd.text.toString(),
                    )
                )
                intent.putExtra(MapActivity.MAP_DATA, GsonUtils.objToJsonStr(mapList))
                startActivity(intent)
            }

        )
        initAdapter()

    }

    private fun initAdapter() {
        val map = hashMapOf(RvSpacesItemUtils.RIGHT_DECORATION to DisplayUtil.dip2px(this, 10f))
        binding.rvFile.addItemDecoration(RvSpacesItemUtils(map))



        binding.rvFile.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        selectPhotoAdapter = SelectPhotoAdapter(this, listener = {


        }, close = {
            photos.removeAt(it)
            selectPhotoAdapter?.notifyDataSetChanged()
        }, datas = photos)
        binding.rvFile.adapter = selectPhotoAdapter
    }


    override fun setContentView() {
        binding = ActivityPumpItemDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    //声明AMapLocationClientOption对象
    private var mLocationOption: AMapLocationClientOption? = null

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null
    private fun startLocation() {
        Log.d(TAG, "startLocation: ===========")
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationClient?.setLocationListener(object : AMapLocationListener {
            override fun onLocationChanged(p0: AMapLocation?) {
                val longitude = "${p0?.longitude}"
                val latitude = "${p0?.latitude}"
                Log.d(TAG, "onLocationChanged: ${longitude} ${latitude}")
                binding.lttd.setText(latitude)
                binding.lgtd.setText(longitude)

            }

        })

        mLocationOption = AMapLocationClientOption()
        val option = AMapLocationClientOption()
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn)
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setOnceLocationLatest(true);

        if (null != mLocationClient) {
            mLocationClient?.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient?.stopLocation()
            mLocationClient?.startLocation()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }


}